//
//  InfoSettingViewController.m
//  EZ Tracker
//
//  Created by FENGYL on 2017/3/22.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

#import "InfoSettingViewController.h"
#import "SettingViewController.h"
#import "MainViewController.h"
#import "UserModel.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import <SVProgressHUD.h>

@interface InfoSettingViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>

@property (strong, nonatomic) UIImage *selectedImage;
@property (strong, nonatomic) UserModel *userModel;

@property (weak, nonatomic) IBOutlet UITextField *deviceNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *countryCodeTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet UIButton *iconButton;

@end

@implementation InfoSettingViewController

-(UserModel *)userModel{
    
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.countryCodeTextField.delegate = self;
    self.phoneNumberTextField.delegate = self;
    self.countryCodeTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneNumberTextField.keyboardType = UIKeyboardTypeNumberPad;
    
    [self setUpPhoneNumber];
    
    //设置deviceName
    if ([self.userModel.changeDeviceNameDictionary valueForKey:self.serialNumber]) {
        
        [self.deviceNameTextField setText:[self.userModel.changeDeviceNameDictionary valueForKey:self.serialNumber]];
        
    }else{
        
        [self.deviceNameTextField setText:self.deviceName];
        
    }
    
    
    
    [self setUpIconForImage:[self.userModel.deviceIconDictionary valueForKey:self.serialNumber]];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 设置号码
-(void)setUpPhoneNumber{
    
    NSDictionary *dict = [self.userModel.msgPhoneNumberDictionary valueForKey:self.serialNumber];
    
    if (dict) {
        
        NSString *countryCodeString = [dict valueForKey:DK_COUNTRY_CODE];
        NSString *phoneNumberString = [dict valueForKey:DK_PHONE_NUMBER];
        
        [self.countryCodeTextField setText:countryCodeString];
        
        [self.phoneNumberTextField setText:phoneNumberString];
        
    }
    
}

#pragma mark 设置头像
-(void)setUpIconForImage:(UIImage *)image{
    
    if (!image) {
        
        image = [UIImage imageNamed:@"ic_tracker_useractivity_yuan_2"];
        
    }
    
    
    [self.iconButton setBackgroundImage:image forState:UIControlStateNormal];
    
}

#pragma mark 检查相册权限
-(void)checkAssetsLibrary{
    
    //相册权限
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author ==ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied){
        //无权限 引导去开启
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Requires album permissions" message:@"Open the album permissions" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"Setting" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
            
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            
            
        }];
        
        [alertController addAction:confirmAction];
        [alertController addAction:cancelAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
        
    }
    
}

#pragma mark 变更头像
- (IBAction)changeUserIcon:(id)sender {
    
    [self checkAssetsLibrary];
    
    //调用系统相册的类
    UIImagePickerController *pickerController = [[UIImagePickerController alloc]init];
    
    
    //设置选取的照片是否可编辑
    pickerController.allowsEditing = YES;
    //设置相册呈现的样式
    pickerController.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;//图片分组列表样式
    //照片的选取样式还有以下两种
    //UIImagePickerControllerSourceTypePhotoLibrary,直接全部呈现系统相册
    //UIImagePickerControllerSourceTypeCamera//调取摄像头
    
    //选择完成图片或者点击取消按钮都是通过代理来操作我们所需要的逻辑过程
    pickerController.delegate = self;
    //使用模态呈现相册
    [self.navigationController presentViewController:pickerController animated:YES completion:^{
        
    }];
    
}

#pragma mark 选择照片完成之后的代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    //info是所选择照片的信息
    
    //    UIImagePickerControllerEditedImage//编辑过的图片
    //    UIImagePickerControllerOriginalImage//原图
    
    
    NSLog(@"%@",info);
    //刚才已经看了info中的键值对，可以从info中取出一个UIImage对象，将取出的对象赋给按钮的image
    
//    UIButton *button = (UIButton *)[self.view viewWithTag:1004];
    
    UIImage *resultImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
//    [button setImage:[resultImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]forState:UIControlStateNormal];//如果按钮创建时用的是系统风格UIButtonTypeSystem，需要在设置图片一栏设置渲染模式为"使用原图"
    
    //压缩图片
    UIImage *newImage = [self imageByScalingAndCroppingForSize:self.iconButton.frame.size withSourceImage:resultImage];
    
    //裁成边角
//    button.layer.cornerRadius = 100;
//    button.layer.masksToBounds = YES;
    
    //开启位图上下文
    UIGraphicsBeginImageContextWithOptions(newImage.size, NO, 0);
    
    //创建圆形路径
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, newImage.size.width, newImage.size.height)];
    
    //设置为裁剪区域
    [path addClip];
    
    //绘制图片
    [newImage drawAtPoint:CGPointZero];
    
    //获取裁剪后的图片
    self.selectedImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭上下文
    UIGraphicsEndImageContext();
    
    [self.iconButton setBackgroundImage:self.selectedImage forState:UIControlStateNormal];
    
    //使用模态返回到软件界面
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
    
    NSLog(@"serialNumber %@",self.serialNumber);
}

#pragma mark 保存设置
- (IBAction)saveInfo:(id)sender {
    
    if (!(_deviceNameTextField.text.length > 0)) {
        
        [SVProgressHUD showErrorWithStatus:@"Device Name can not be empty"];
        
        [SVProgressHUD dismissWithDelay:1];
        
        return;
        
    }
    
    if (_selectedImage) {
        
        NSLog(@"serialNumber %@",self.serialNumber);
        
        [self.userModel.deviceIconDictionary setValue:_selectedImage forKey:self.serialNumber];
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        
            NSString *filePath = [path stringByAppendingPathComponent:ARCHIVER_DEVICE_ICON_DICTIONARY];
        
            [NSKeyedArchiver archiveRootObject:self.userModel.deviceIconDictionary toFile:filePath];
            
        });
        
        
        
        if ([[self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count) - 2] isKindOfClass:[SettingViewController class]]) {
            
            SettingViewController * settingViewController = [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count) - 2];
            
            [settingViewController reloadTableView];
            
        }
        
        if ([[self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count) - 3] isKindOfClass:[MainViewController class]]) {
            
            MainViewController *mainViewController = [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count) - 3];
            
            [mainViewController reloadTableViewOrCollectionView];
            
        }
        
        
    }
    
    
    //号码
    NSString *countryCodeString = self.countryCodeTextField.text;
    
    NSString *phoneNumberString = self.phoneNumberTextField.text;
    
    NSDictionary *msgDictionary = @{DK_COUNTRY_CODE:countryCodeString,DK_PHONE_NUMBER:phoneNumberString};
    
    [self.userModel.msgPhoneNumberDictionary setValue:msgDictionary forKey:self.serialNumber];
    
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString *filePath = [path stringByAppendingPathComponent:ARCHIVER_MSG_PHONE_NUMBER_DICTIONARY];
        
        [NSKeyedArchiver archiveRootObject:self.userModel.msgPhoneNumberDictionary toFile:filePath];
        
    });
    
    
    
    //设备名
    NSString *deviceName = self.deviceNameTextField.text;
    
    [self.userModel.changeDeviceNameDictionary setValue:deviceName forKey:self.serialNumber];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString *filePath = [path stringByAppendingPathComponent:ARCHIVER_CHANGE_DEVICE_NAME_DICTIONARY];
        
        [NSKeyedArchiver archiveRootObject:self.userModel.changeDeviceNameDictionary toFile:filePath];
        
    });
    
    if ([[self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count) - 2] isKindOfClass:[SettingViewController class]]) {
        
        SettingViewController * settingViewController = [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count) - 2];
        
        [settingViewController reloadTableView];
        
    }
    
    if ([[self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count) - 3] isKindOfClass:[MainViewController class]]) {
        
        MainViewController *mainViewController = [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count) - 3];
        
        [mainViewController reloadTableViewOrCollectionView];
        
    }
    
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 压缩图片
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withSourceImage:(UIImage *)sourceImage
{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    
    return newImage;
}

#pragma mark 只能输入数字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return [self validateNumber:string];
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
